﻿using UnityEngine;
using System.Collections;

public class HealthBar : MonoBehaviour {
    
	// Use this for initialization
    Vector3 initialPos;
    public Texture2D texture;
    public float width, height, offsetX, offsetY;
    private float initialHeight, initialWidth;
    public enum Orientation { Horizontal, Vertical };
    public Orientation orientation = Orientation.Horizontal;

    int CurrHealth, Health;
	void Start () 
	{
        texture = (Texture2D) Resources.Load("healthbar2");
        initialPos = gameObject.transform.position;
        initialWidth = width;
        initialHeight = height;
        //print(GetComponent<CanTakeDamage>().Health) ;
        //print(GetComponent<AIBase>() is CanTakeDamage);
	}

    void OnGUI()
    {
        if (gameObject.GetComponent<CanTakeDamage>() != null)
        {
            CurrHealth = GetComponent<CanTakeDamage>().CurrHealth;   
            Health = GetComponent<CanTakeDamage>().Health;
        }
        Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);
        if (((float)CurrHealth / Health) > .6f)
        {
            GUI.color = Color.green;
        }
        else if (((float)CurrHealth / Health) < .33f)
        {
            GUI.color = Color.red;
        }
        else
        {
            GUI.color = Color.yellow;
        }
        if (orientation == Orientation.Horizontal)
        {
            if ((Screen.height / initialHeight) > (Screen.width / initialWidth))
            {
                GUI.DrawTexture(new Rect(pos.x + (Screen.width / offsetX), Screen.height - pos.y + (Screen.height / offsetY), (-Screen.height / initialHeight) * ((float)CurrHealth / Health), Screen.width / width), texture);
            }
            else
            {
                GUI.DrawTexture(new Rect(pos.x + (Screen.width / offsetX), Screen.height - pos.y + (Screen.height / offsetY), (-Screen.width / initialWidth) * ((float)CurrHealth / Health), Screen.height / height), texture);
            }
        }
        else
        {
            if ((Screen.height / initialHeight) > (Screen.width / initialWidth))
            {
                GUI.DrawTexture(new Rect(pos.x + (Screen.width / offsetX), Screen.height - pos.y + (Screen.height / offsetY), (-Screen.width / width), (-Screen.height / initialHeight) * ((float)CurrHealth / Health)), texture);
            }
            else
            {
                GUI.DrawTexture(new Rect(pos.x + (Screen.width / offsetX), Screen.height - pos.y + (Screen.height / offsetY), (-Screen.height / height), (-Screen.width / initialWidth) * ((float)CurrHealth / Health)), texture);
            }
        }
            // GUI.Box(new Rect(pos.x, Screen.height - pos.y, width, height), "");

    }
}
